using UnityEngine;
using System.Collections;

/// \class  gkRestartOnPlayerDeath
/// \brief  Handle the player death event
[AddComponentMenu("GK/Engine/Game/Player/Death/gkRestartOnPlayerDeath")]
public class gkRestartOnPlayerDeath : MonoBehaviour 
{
	/// The duration of the death screen before restart
	public float BeforeRestartDuration = 3.0f;
	
	/// The current time since death
	private float m_fTimeSinceDeath; 
	
	/// Is the owner dead
	private bool m_bDead;
	
	/// \brief  Called when the component is enabled
	void OnEnable() 
	{
		// Listen the shock event of the owner
		GetComponent<gkEventComponent>().AddEventHandler(gkPlayerEvent.PlayerDeath, HandlePlayerDeathEvent);
	}
	
	/// \brief  Called when the component is disabled
	void OnDisable() 
	{	
		// Remove the shock event of the owner
		GetComponent<gkEventComponent>().RemoveEventHandler(gkPlayerEvent.PlayerDeath, HandlePlayerDeathEvent);
	}
	
	/// \brief  Called each frame
	void Update()
	{
		// If the player is dead, wait a little amount of time before restart
		if(m_bDead)
		{
			m_fTimeSinceDeath += Time.deltaTime;
			if(Input.GetButtonDown("Select") || m_fTimeSinceDeath > BeforeRestartDuration)
			{
				Application.LoadLevel(Application.loadedLevel);
			}
		}
	}
	
	/// Handle the player death event
	void HandlePlayerDeathEvent(Object a_rEvent)
	{
		m_bDead = true;
	}
}
